package net.tribal.comic.controllers

import net.tribal.comic.entities.Comic
import net.tribal.comic.entities.Comment
import net.tribal.comic.entities.Rate
import net.tribal.comic.entities.User

class ComicController {
	def comicService
	
	
	/**
     *  Les accions 'delete', 'save' i 'update' nom�s accepten peticions POST
     */
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
                             
                             
	/**
	 * Acci� per defecte
	 */
    def index = { redirect(controller:"comic", action:"list", params:params) }
	
	
	/**
     * Commuta entre entre el modes de visionat "Coverflow" i "Llistat" 
     */
	def changeView = {
		session['comicViewMode'] = (session['comicViewMode'] == 'list') ? "flow" : "list"
		redirect(controller:"comic", action: "list", params: params)
		return
	}
	

    /**
     *
     */
    def list = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def list = comicService.getActiveComics(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.searchAjax)
		
		if(params.searchAjax != null){
		    //	La cerca es as�ncrona
			render(template:"/comic/listContent", model: [comicInstanceList:list['data'], comicInstanceTotal:list['count']])
			return
		} 
		
		// La cerca es s�ncrona
		render(view:"/comic/list", model:[comicInstanceList: list['data'], comicInstanceTotal: list['count']])
		return 
    }

	
    /**
     * 
     */
    def create = {
        def comicInstance = new Comic()
        comicInstance.properties = params
        render(view:"/comic/create", model:[comicInstance: comicInstance])
        return 
    }


	/**
	 * 
	 */
    def save = {
		def comicInstance = new Comic(params)
		comicInstance.createdBy = session['user']
        comicService.add( comicInstance, request.getFile('file') )
        if ( !comicInstance.hasErrors() ) {
            flash.message = "flash.comic.created"
            redirect(controller:"comic", action:"list")
            return
        }

		render(view:"/comic/create", model: [comicInstance: comicInstance])
        return
    }

    def show = {
        def comicInstance = Comic.get(params.id)
        if (!comicInstance) {
            flash.message = "flash.comic.not.found"
            flash.args = [params.id]
            redirect(controller:"comic", action: "list")
            return
        }
    	def userSession = User.get(session.user?.ident())
    	def yourOldRate = comicService.getRateOldRate ( comicInstance, userSession )
		
		def admin = session.user?.admin
		def bestPages = comicInstance.getBestPages(admin)
    	
        render(view:"/comic/show", model:[comicInstance: comicInstance, 'yourRate':yourOldRate, bestPages:bestPages])
        return 
    }


	def editProfile = {
        def comicInstance = Comic.get(params.id)
        if (!comicInstance) {
            flash.message = "flash.comic.not.found"
            flash.args = [params.id]
            redirect(controller:"comic", action: "list")
            return
        }
        
		render (view:"/comic/editProfile", model:[comicInstance: comicInstance] )
		return
    }

	
	/**
     * M�tode que mostra la pantalla per canviar l'imatge d'un comic
     * 
     * retun
     * 	redirect - /comic/list
     *  render - /comic/editProfile
     */
	def editFile = {
        def comicInstance = Comic.get(params.id)
        if (!comicInstance) {
            flash.message = "flash.comic.not.found"
            flash.args = [params.id]
            redirect(controller:"comic", action:"list")
            return
        }

        render (view:"/comic/editFile", model:[comicInstance: comicInstance] )
        return
    }
	
	
	/**
	 * Actualitza les dades d'un comic
	 * 
	 * retun
     * 	redirect - /comic/list
     *  render - /comic/edit
     *  redirect - /comic/show
	 */
	def updateProfile = {
		def comicInstance = Comic.get (params.id)
		
		if ( !comicInstance ) {
			flash.message = "flash.comic.not.found"
            flash.args = [params.id]
            redirect(controller:"comic", action:"list")
            return
		}

		comicInstance.properties = params
		comicInstance = comicService.changeProfile( comicInstance )

		if ( comicInstance.hasErrors() ) {
			render(view:"/comic/editProfile", model:[comicInstance: comicInstance])
			return
    	}
		
		flash.message = "flash.comic.updated"
        redirect(controller:"comic", action:"show", id: comicInstance.id)
    	return
	}
	
	
	/**
	 * Actualitza l'imatge del comic
	 * 
	 * retun
     * 	redirect - /comic/list
     *  render - /comic/editFile
     *  redirect - /comic/show
	 */
	def updateFile = {
		def comicInstance = Comic.get (params.id)
		if ( !comicInstance ) {
			flash.message = "flash.comic.not.found"
            flash.args = [params.id]
            redirect(controller:"comic", action:"list")
            return
		}

		comicInstance = comicService.changeFile ( comicInstance, request.getFile('file') )

		if ( comicInstance.hasErrors() ) {
			render(view:"/comic/editFile", model: [comicInstance: comicInstance])
			return
    	}
		
		flash.message = "comic.updated"
        redirect(controller:"comic", action:"show", id: comicInstance.id)
    	return
	}

	
	/**
	 * Elimina un comic
	 * 
	 * retun
     * 	redirect - /comic/list
     *  redirect - /comic/show
	 */
    def delete = {
		def comicInstance = comicService.delete( Comic.get(params.id) )
		
        if (!comicInstance) {
			flash.message = "flash.comic.not.found"
			flash.args = [params.id]
			redirect(controller:"comic", action:"list")
			return
		}
		
		if (!comicInstance.hasErrors()) {
            flash.message = "flash.comic.deleted"
            flash.args = [params.id]
            redirect(controller:"comic", action:"list")
            return
		
		} 

        flash.message = "flash.comic.not.deleted"
        flash.args = [params.id]
        redirect(controller:"comic", action:"show", id: params.id)
        return
    }
	
	
	/**
	 * 
	 */
    def enable = {
		def instance = Comic.get(params.id)
		if ( !instance ) {
			flash.message = "flash.comic.not.found"
			flash.args = [params.id]
			redirect(controller:"comic", action:"list")
			return
		}
		
		instance.disabled = false
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.comic.updated"
            redirect(controller:"comic", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"comic", action:"show", id:instance.id)
		return
    }


	/**
	 * 
	 */
    def disable = {
		def instance = Comic.get(params.id)
		if ( !instance ) {
			flash.message = "flash.comic.not.found"
			flash.args = [params.id]
			redirect(controller:"comic", action:"list")
			return
		}
		
		instance.disabled = true
		instance.moderationRequest = false
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.comic.updated"
            redirect(controller:"comic", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"comic", action:"show", id:instance.id)
		return
    }


	/**
	 * Sol�licita moderacio per un comic
	 * 
	 * retun
     *  redirect - /comic/show
     *  redirect - /comic/list
	 */
	def moderationRequest = {
		def instance = Comic.get(params.id)
		if ( !instance ) {
			flash.message = "flash.comic.not.found"
			flash.args = [params.id]
			redirect(controller:"comic", action:"list")
			return
		}
		
		instance.moderationRequest = true
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.comic.moderation.request"
            redirect(controller:"comic", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"comic", action:"show", id:instance.id)
		return
    }
	
	
	/**
	 * Valida que es correcte el comic
	 * 
	 * retun
     *  redirect - /comic/show
     *  redirect - /comic/list
     *  redirect - /user/moderationRequests
	 */
	def moderate = {
		def instance = Comic.get(params.id)
		if ( !instance ) {
			flash.message = "flash.comic.not.found"
			flash.args = [params.id]
			redirect(controller:"comic", action:"list")
			return
		}
		
		instance.moderationRequest = false
		
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.comic.moderation.request"
            redirect(controller:"user", action:"moderationRequests")
			return
		}
			
		redirect(controller:"comic", action:"show", id:instance.id)
		return
    }
	
	
	/**
	 * Mostra els comentatis d'una comic
	 * 
	 * retun
     *  render - /comic/list
	 */
    def comments = {
        params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
        
        def list = comicService.getComicComments(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.commentToId)
	    
        render(template:"/comment/list", model:[commentInstanceList: list['data'], commentInstanceTotal:list['count'], commentToName:'comic', commentToId:params.commentToId])
        return
    }
	
	
	/**
	 * Afegeix un comentati a un comic
	 * 
	 * retun
     *  render - /comic/create
     *  redirect - /comic/comments
	 */
	def addComment = {
		def comment = new Comment(params)
		comment.createdBy = session['user']
		                            
		//	Si t� errors, mostrem la pantalla de creaci� d'un comentari.
        if (comment.hasErrors() ) {
    		render(template:"/comment/create", model:[commentInstance:comment, commentToName:params.commentToName, commentToId:params.commentToId])
    		return
        }
        
        def comic = Comic.get(params.commentToId.toLong())
		comic.addToComments(comment)
        
        flash.message = "flash.comment.saved"
        redirect(controller:"comic", action:"comments", params:[commentToId:params.commentToId])
        return
	}

	
	/**
	 * Afegeix un vot a un usuari
	 * Si es la primera vegada que un usuari vota a un usuari en concret, afegeix un vot
	 * si no, actualiza el vot
	 * 
	 * retun
	 *  render - /rate/rate
	 */
	def rate = {
		def comic = Comic.get(params.id)
		def userSession = User.get(session.user.ident())

		if(comicService.rate(params.rating, comic, userSession)){
			//	Es puntua correctament
			render(template: "/rate/rateCustom", model:[instance: comic, from:'comic', yourRate:params.rating])
			return
		}else{
			//	Error al puntuar
			comic.errors.rejectValue("", "rate.fault")	
			render(template: "/rate/rateCustom", model:[instance: comic, from:'comic', yourRate:params.rating])
			return
		}
	}

	
	/**
	 * Metode que busca la secuencia de pagines d'un comic millor puntuades.
	 * 
	 * Per cada pagina d'un comic:
	 *  Si una pagina te alguna pagina alternativa, i te millor puntuacio, mostra la pagina alternativa,
	 *  sino, mostra la pagina
	 *  
	 *  retun
     *   render - /page/best
	 */
	def bestPages = {
		def comic = Comic.get(params.id)
		def admin = session.user?.admin
		
		def result = comic.getBestPages(admin)
		
        
		render(view:"/page/best", model:[instanceList:result, instanceTotal:result.size(), title:comic.title])
		return
	}
}